package com.cicadamob.contact.api.service.BlackName;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.cicadamob.contact.api.Utils.StringUtil;
import com.cicadamob.contact.api.Utils.pinyin.PinyinTools;
import com.cicadamob.contact.api.service.APPContactDao;
import com.cicadamob.contact.api.service.Contact;
import com.cicadamob.contact.api.service.SysContactDao;
import com.cicadamob.contact.api.service.BlackName.BlackName_DbHelper.TS_BLACK_NAME;
import com.cicadamob.contact.api.service.BlackName.BlackName_DbHelper.TS_INTERCEPT_HISTORY;

/**
 * 电话拦截数据库相关操作
 * 
 * @author Administrator
 * 
 */
public class BlackName_Db_Dao {
	private static BlackName_DbHelper dbHelper;
	private Context context;
	private static BlackName_Db_Dao db_dao = null;
	private SQLiteDatabase db;
	private AtomicInteger mOpenCounterRead = new AtomicInteger();
	private AtomicInteger mOpenCounterWrite = new AtomicInteger();

	private BlackName_Db_Dao(Context context) {
		this.context = context;
		dbHelper=BlackName_DbHelper.newInstance(context);
	}

	public static synchronized BlackName_Db_Dao getInstance(Context context) {
		if (db_dao == null || dbHelper==null) {
			db_dao = new BlackName_Db_Dao(context);
		}
		return db_dao;

	}

	private synchronized SQLiteDatabase getWritableDatabase() {
		if (mOpenCounterWrite.incrementAndGet() == 1) {
			// Opening new database
//			db = DBManager.getInstance(context).openDatabase();
			db=dbHelper.getWritableDatabase();
		} 
		return db;   
	}

	private synchronized SQLiteDatabase getReadableDatabase() {
		if (mOpenCounterRead.incrementAndGet() == 1) {
			// Opening new database
//			db = DBManager.getInstance(context).openDatabase();
			db=dbHelper.getReadableDatabase();
		}
		return db;
	}

	private synchronized void closeDB() {
		if (mOpenCounterRead.decrementAndGet() == 0
				&& mOpenCounterWrite.decrementAndGet() == 0) {
			// Closing database
			if (db != null) {
				db.close();
			}
		}
	}


/**
 * 根据电话号码删除黑名单(拦截记录)
 * @param phoneNumber
 * @return
 */
	public int delBlackNameByPhone(String phoneNumber) {
		int id = 0;
		db = getWritableDatabase();
		id = db.delete(BlackName_DbHelper.TABLE_BLACK_NAME, TS_BLACK_NAME.TEL + "=?",
				new String[] { phoneNumber });
//		db.delete(BlackName_DbHelper.TABLE_INTERCEPT_HISTORY, TS_INTERCEPT_HISTORY.TEL+"=?", new String[] { phoneNumber });
		closeDB();
		return id;
	}

	/**
	 * 根据电话号码删除拦截记录
	 * @param phoneNumber
	 * @return
	 */
		public int delInteceptHistoryByPhone(String phoneNumber) {
			int id = 0;
			db = getWritableDatabase();
		
			db.delete(BlackName_DbHelper.TABLE_INTERCEPT_HISTORY, TS_INTERCEPT_HISTORY.TEL+"=?", new String[] { phoneNumber });
			closeDB();
			return id;
		}
	


	/**
	 * 删除全部记录
	 */
	public void delAll() {
		db = getWritableDatabase();
		db.delete(BlackName_DbHelper.TABLE_BLACK_NAME, null, null);
		db.delete(BlackName_DbHelper.TABLE_INTERCEPT_HISTORY, null, null);
		closeDB();
	}



	/**
	 * 插入黑名单
	 * @param blackNames
	 */
	private void insertBlackName(List<Contact> blackNames) {
		db = getWritableDatabase();
		db.isDbLockedByOtherThreads();	
		try {
			for(Contact bean : blackNames){
				ContentValues values=new ContentValues();
				values.put(TS_BLACK_NAME.NAME, bean.getDisplayName());
				values.put(TS_BLACK_NAME.TEL, bean.getLinkPhone());
				values.put(TS_BLACK_NAME.Type, bean.getBlackNameType());
				values.put(TS_BLACK_NAME.Photo, bean.getImagepath());
				values.put(TS_BLACK_NAME.Installed,bean.getInstall());
				db.insert(BlackName_DbHelper.TABLE_BLACK_NAME, null, values);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			closeDB();
		}
	}

	/**
	 * 插入黑名单
	 * @param blackNames
	 */
	public void insertBlackName(Contact bean) {
		db = getWritableDatabase();
		db.isDbLockedByOtherThreads();	
		try {
			ContentValues values=new ContentValues();
			String phone=filterPhone(bean.getLinkPhone());
			values.put(TS_BLACK_NAME.NAME, bean.getDisplayName());
			values.put(TS_BLACK_NAME.TEL, phone);
			values.put(TS_BLACK_NAME.Type, bean.getBlackNameType());
			values.put(TS_BLACK_NAME.Photo, bean.getImagepath());
			values.put(TS_BLACK_NAME.Installed,bean.getInstall());
			db.insert(BlackName_DbHelper.TABLE_BLACK_NAME, null, values);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			closeDB();
		}
	}
	
	/**
	 * 黑名单是否已存在
	 * @param phone
	 * @return
	 */
	public boolean isBlackNameExist(String phone){
		
		return isBlackName(phone);
		
	}
	

	/**
	 * 查询黑名单
	 * 
	 * @return
	 */
	public List<Contact> queryAllBlackName() {
		List<Contact> nameList = new ArrayList<Contact>();
		Map<String,String> contactMap=APPContactDao.getContactAllPhoneNameMap(context);
		db = getReadableDatabase();
		Cursor c = null;
		try {
			c = db.query(BlackName_DbHelper.TABLE_BLACK_NAME, null, null, null, null, null,
					TS_BLACK_NAME.ID + " DESC");
			if (c != null && c.getCount() > 0) {
				while (c.moveToNext()) {
					Contact bean = new Contact();
				    bean.setDisplayName(c.getString(c.getColumnIndex(TS_BLACK_NAME.NAME)));
				    bean.setLinkPhone(c.getString(c.getColumnIndex(TS_BLACK_NAME.TEL)));
				    bean.setImagepath(c.getString(c.getColumnIndex(TS_BLACK_NAME.Photo)));
				    bean.setBlackNameType(c.getInt(c.getColumnIndex(TS_BLACK_NAME.Type)));
				    bean.setInstall(c.getInt(c.getColumnIndex(TS_BLACK_NAME.Installed)));
				    if(!StringUtil.isEmpty(bean.getLinkPhone()) && contactMap.containsKey(bean.getLinkPhone())){
				    	bean.setDisplayName(contactMap.get(bean.getLinkPhone()));
				    }
				    String displayName=bean.getDisplayName();
					if(StringUtil.isEmpty(displayName)){
						bean.setLetter("#");
					}else{
						String letter=PinyinTools.getFirstCharPinYin(displayName.substring(0, 1));
						char[] firstChar= letter.toCharArray();
						if(firstChar!=null&&firstChar.length>0){
							if(firstChar[0]>='a'&&firstChar[0]<='z'){
								bean.setLetter(letter.toUpperCase());
							}else if(firstChar[0]>='A'&&firstChar[0]<='Z'){
								bean.setLetter(letter);
							}else{
								bean.setLetter("#");
							}
						}
					}
					nameList.add(bean);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (c != null) {
				c.close();
			}
			closeDB();
		}
		return nameList;
	}
	/**
	 * 根据电话号码查询黑名单
	 * @param phone
	 * @return  null 表示没有查询到
	 */
	public  Contact queryBlackNameByPhone(String phone) {
		Contact bean = null;
		db = getReadableDatabase();
		Cursor c = null;
		try {
			c = db.query(BlackName_DbHelper.TABLE_BLACK_NAME, null, TS_BLACK_NAME.TEL+"=?", new String[]{phone}, null, null,
					TS_BLACK_NAME.ID + " DESC");
			if (c != null && c.getCount() > 0) {
				   if(c.moveToNext()){
					   bean = new Contact();
					    bean.setDisplayName(c.getString(c.getColumnIndex(TS_BLACK_NAME.NAME)));
					    bean.setLinkPhone(c.getString(c.getColumnIndex(TS_BLACK_NAME.TEL)));
					    bean.setImagepath(c.getString(c.getColumnIndex(TS_BLACK_NAME.Photo)));
					    bean.setBlackNameType(c.getInt(c.getColumnIndex(TS_BLACK_NAME.Type)));
					    bean.setInstall(c.getInt(c.getColumnIndex(TS_BLACK_NAME.Installed))); 
					    String displayName=bean.getDisplayName();
						if(StringUtil.isEmpty(displayName)){
							bean.setLetter("#");
						}else{
							String letter=PinyinTools.getFirstCharPinYin(displayName.substring(0, 1));
							char[] firstChar= letter.toCharArray();
							if(firstChar!=null&&firstChar.length>0){
								if(firstChar[0]>='a'&&firstChar[0]<='z'){
									bean.setLetter(letter.toUpperCase());
								}else if(firstChar[0]>='A'&&firstChar[0]<='Z'){
									bean.setLetter(letter);
								}else{
									bean.setLetter("#");
								}
							}
						}
				   }
					
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (c != null) {
				c.close();
			}
			closeDB();
		}
		return bean;
	}
	
	
    /**
     * 根据电话号码查询拦截记录
     * @param phoneNumber
     * @return
     */
	public List<Contact> queryInterceptHistoryByPhone(String phoneNumber){
		List<Contact> nameList = new ArrayList<Contact>();
		db = getReadableDatabase();
		Cursor c = null;
		try {
			c = db.query(BlackName_DbHelper.TABLE_INTERCEPT_HISTORY, null, TS_INTERCEPT_HISTORY.TEL+"=?", new String[]{phoneNumber}, null, null,
					TS_INTERCEPT_HISTORY.ID + " DESC");
			if (c != null && c.getCount() > 0) {
				while (c.moveToNext()) {
					Contact bean = new Contact();
				    bean.setDisplayName(c.getString(c.getColumnIndex(TS_INTERCEPT_HISTORY.NAME)));
				    bean.setLinkPhone(c.getString(c.getColumnIndex(TS_INTERCEPT_HISTORY.TEL)));
				    bean.setImagepath(c.getString(c.getColumnIndex(TS_INTERCEPT_HISTORY.Photo)));
				    bean.setBlackNameType(c.getInt(c.getColumnIndex(TS_INTERCEPT_HISTORY.Type)));
				    bean.setInterectTime(c.getLong(c.getColumnIndex(TS_INTERCEPT_HISTORY.Time)));
					nameList.add(bean);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (c != null) {
				c.close();
			}
			closeDB();
		}
		return nameList;
	}
	
	
	
	

	
	/**
	 * 查询拦截记录
	 * @return
	 */
		public List<Contact> queryInterceptHistory(boolean isGroupbyPhone){
			List<Contact> nameList = new ArrayList<Contact>();
			db = getReadableDatabase();
			Cursor c = null;
			try {
				if(isGroupbyPhone){
					c = db.query(BlackName_DbHelper.TABLE_INTERCEPT_HISTORY, null, null, null, TS_INTERCEPT_HISTORY.TEL, null,
							TS_INTERCEPT_HISTORY.ID + " DESC");
				}else{
					c = db.query(BlackName_DbHelper.TABLE_INTERCEPT_HISTORY, null, null, null, null, null,
							TS_INTERCEPT_HISTORY.ID + " DESC");	
				}
				
				if (c != null && c.getCount() > 0) {
					while (c.moveToNext()) {
						Contact bean = new Contact();
					    bean.setDisplayName(c.getString(c.getColumnIndex(TS_INTERCEPT_HISTORY.NAME)));
					    bean.setLinkPhone(c.getString(c.getColumnIndex(TS_INTERCEPT_HISTORY.TEL)));
					    bean.setImagepath(c.getString(c.getColumnIndex(TS_INTERCEPT_HISTORY.Photo)));
					    bean.setBlackNameType(c.getInt(c.getColumnIndex(TS_INTERCEPT_HISTORY.Type)));
					    bean.setInterectTime(c.getLong(c.getColumnIndex(TS_INTERCEPT_HISTORY.Time)));
						nameList.add(bean);
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				if (c != null) {
					c.close();
				}
				closeDB();
			}
			return nameList;
		}
	
	
		/**
		 * 插入拦截记录
		 * @param intercept
		 */
		public void insertIntercept(List<Contact> interceptList) {
			db = getWritableDatabase();
			db.isDbLockedByOtherThreads();	
			try {
				for(Contact bean : interceptList){
					ContentValues values=new ContentValues();
					values.put(TS_INTERCEPT_HISTORY.NAME, bean.getDisplayName());
					values.put(TS_INTERCEPT_HISTORY.TEL, bean.getLinkPhone());
					values.put(TS_INTERCEPT_HISTORY.Type, bean.getBlackNameType());
					values.put(TS_INTERCEPT_HISTORY.Photo, bean.getImagepath());
					values.put(TS_INTERCEPT_HISTORY.Time, System.currentTimeMillis());
					db.insert(BlackName_DbHelper.TABLE_INTERCEPT_HISTORY, null, values);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				closeDB();
			}
		}
		
		/**
		 * 单条插入拦截记录
		 * @param intercept
		 */
		public void insertIntercept(Contact bean) {
			db = getWritableDatabase();
			db.isDbLockedByOtherThreads();	
			try {
				ContentValues values=new ContentValues();
				values.put(TS_INTERCEPT_HISTORY.NAME, bean.getDisplayName());
				values.put(TS_INTERCEPT_HISTORY.TEL, bean.getLinkPhone());
				values.put(TS_INTERCEPT_HISTORY.Type, bean.getBlackNameType());
				values.put(TS_INTERCEPT_HISTORY.Photo, bean.getImagepath());
				values.put(TS_INTERCEPT_HISTORY.Time, System.currentTimeMillis());
				db.insert(BlackName_DbHelper.TABLE_INTERCEPT_HISTORY, null, values);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				closeDB();
			}
		}
		
		/**
		 * 判断电话号码是否是黑名单
		 * @param phone
		 * @return
		 */
	 public boolean isBlackName(String phone){
		 boolean isBlackName=false;
		if (StringUtil.isEmpty(phone)) {
			return false;
		}
		phone=filterPhone(phone);
		if (StringUtil.isEmpty(phone)) {
			return false;
		}
		 
		 db = getReadableDatabase();
			Cursor c = null;
			try {
				c = db.query(BlackName_DbHelper.TABLE_BLACK_NAME, null, TS_BLACK_NAME.TEL+"=?", new String[]{phone}, null, null,
						TS_BLACK_NAME.ID + " DESC");
				if (c != null && c.getCount() > 0) {
					isBlackName=true;
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				isBlackName=false;
			} finally {
				if (c != null) {
					c.close();
				}
				closeDB();
			}
		 
		 return isBlackName;
	 }
	 
		/**
		 * 判断电话号码是否是黑名单
		 * @param phone
		 * @return null 表示没查询到
		 */
	 public Contact isBlackNameNumber(String phone){
		 Contact bean=null;
		 db = getReadableDatabase();
			Cursor c = null;
			try {
				c = db.query(BlackName_DbHelper.TABLE_BLACK_NAME, null, TS_BLACK_NAME.TEL+"=?", new String[]{phone}, null, null,
						TS_BLACK_NAME.ID + " DESC");
				if (c != null && c.getCount() > 0) {
					   if(c.moveToNext()){
						    bean = new Contact();
						    bean.setDisplayName(c.getString(c.getColumnIndex(TS_BLACK_NAME.NAME)));
						    bean.setLinkPhone(c.getString(c.getColumnIndex(TS_BLACK_NAME.TEL)));
						    bean.setImagepath(c.getString(c.getColumnIndex(TS_BLACK_NAME.Photo)));
						    bean.setBlackNameType(c.getInt(c.getColumnIndex(TS_BLACK_NAME.Type)));
						    bean.setInstall(c.getInt(c.getColumnIndex(TS_BLACK_NAME.Installed))); 
						    
					   }
					 
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				 
			} finally {
				if (c != null) {
					c.close();
				}
				closeDB();
			}
		 
		 return bean;
	 }
	 
	 /**
	  * 查询全部黑名单电话
	  * @return
	  */
		public List<String> queryAllBlackPhone() {
			List<String> phoneList = new ArrayList<String>();
			db = getReadableDatabase();
			Cursor c = null;
			try {
				c = db.query(BlackName_DbHelper.TABLE_BLACK_NAME, null, null, null, null, null,
						TS_BLACK_NAME.ID + " DESC");
				if (c != null && c.getCount() > 0) {
					while (c.moveToNext()) {
					    String phone=c.getString(c.getColumnIndex(TS_BLACK_NAME.TEL));
						if(!phoneList.contains(phone)){
							phoneList.add(phone);
						}
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				if (c != null) {
					c.close();
				}
				closeDB();
			}
			return phoneList;
		}
		
		
		private String filterPhone(String phone){
			if(StringUtil.isEmpty(phone)){
				return "";
			}
			if (phone.contains(" ")) {
				phone = phone.replace(" ", "");
			}
			// 去横杠
			if (phone.contains("-")) {
				phone = phone.replace("-", "");
			}
			// 去“+86”前缀
			if (phone.contains("+86")) {
				phone = phone.replace("+86", "");
			}
			
			return phone;
		}
}
